package com.my.rouge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.rouge.mapper.UserMapper;
import com.my.rouge.pojo.User;
import com.my.rouge.service.UserService;
import com.my.rouge.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    //通过手机号查询用户信息
    @Override
    public User queryUserByPhone(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        User user = userMapper.selectOne(wrapper);
        return user;
    }


    //注册操作
    @Override
    public void addUser(User user) {
        String time = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        user.setTime(time);
        //如果没有name给随机数
        if (user.getName() == null){
            Random random = new Random();
            int i = random.nextInt(10000);
            user.setName("用户" + i);
        }
        userMapper.insert(user);
    }

    //修改名称
    @Override
    public void updateUserName(User user) {
        userMapper.updateById(user);
    }

    //获取所有用户信息
    @Override
    public Page<User> getAll(Integer pageNum,Integer pageSize,String queryInput) {
        Page<User> userPage = new Page<>(pageNum,pageSize);
        System.out.println(queryInput);
        if (queryInput == null){
            return userMapper.selectPage(userPage,null);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",queryInput).or().like("phone",queryInput);
        return userMapper.selectPage(userPage,queryWrapper);
    }

    @Override
    public List<User> getUser() {
        return userMapper.selectList(null);
    }
}
